﻿using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using Kiiro.Common.Entities;
using Kiiro.Common.Utility;
using Kiiro.Model;
using Kiiro.SiteDefinition.ControlTemplates;
using Kiiro.SiteDefinition.Core;

using PortalFileUrls = Kiiro.Common.Utility.Constants.PortalFileUrls;
using System.Web.UI;
using Microsoft.SharePoint.Utilities;
using System.Web.UI.HtmlControls;

namespace Kiiro.SiteDefinition.PortalPages
{
    public partial class AllUsers : BasePage
    {
        #region Properties
        private List<User> users = new List<User> ( );
        private List<User> Users
        {
            get { return users; }
            set { users = value; }
        }

        public Pager V2Pager
        {
            get { return ( Pager ) v2Pager; }
        }

        public NavigationSub NavigationSub
        {
            get { return KiiroMaster.NavigationSub; }
        }
        #endregion

        #region Page Events
        protected void Page_Load ( object sender, EventArgs e )
        {
            litTitle.Text = "Users and Groups";

            if ( PermissionBitsUsers [ 0 ] || PermissionBitsUsers [ 3 ] )
            {
                AddCommandButtons ( );

                V2Pager.NextClick += new EventHandler ( RePopulatePage );
                V2Pager.PrevClick += new EventHandler ( RePopulatePage );
                V2Pager.EntitiesPerPageChange += new EventHandler ( RePopulatePage );

                Users = UserModel.GetUsersFromSPGroups ( SiteCollectionId, ServerRelativeUrl );

                if ( !IsPostBack )
                {
                    V2Pager.SortExpression = "Name";
                    PopulatePage ( );
                }
            }
            else
                Response.Redirect ( String.Format ( "{0}/default.aspx", ServerRelativeUrl ) );
        }
        #endregion

        #region Control Events
        protected void btnCreateUser_Click ( object sender, EventArgs e )
        {
            Response.Redirect ( String.Format ( "{0}{1}", ServerRelativeUrl, PortalFileUrls.UserNew ) );
        }

        protected void btnCreateGroup_Click ( object sender, EventArgs e )
        {
            Response.Redirect ( String.Format ( "{0}{1}", ServerRelativeUrl, PortalFileUrls.GroupNew ) );
        }

        protected void btnDelete_Click ( object sender, EventArgs e )
        {
            LinkButton btnDelete = ( LinkButton ) sender;
            int spUserId = int.Parse ( btnDelete.CommandArgument );

            User user = UserModel.GetOrCreateUser ( spUserId, SiteCollectionId, ServerRelativeUrl );

            user.ModifiedBy = CurrentUser;
            user.EditType = EditType.Deleted;

            UserModel.Save ( user, SiteCollectionId, ServerRelativeUrl );

            if ( user.IsValid ( ) )
                Response.Redirect ( String.Format ( "{0}{1}", ServerRelativeUrl, PortalFileUrls.UserAll ) );
            else
                KiiroMaster.V2ErrorsList.ErrorMessages.Add ( FormattingHelpers.GetErrorMessageText ( user.EditTypeMessage ) );
        }

        protected void btnEdit_Click ( object sender, EventArgs e )
        {
            LinkButton btnEdit = ( LinkButton ) sender;
            int spUserId = int.Parse ( btnEdit.CommandArgument );

            User user = UserModel.GetOrCreateUser ( spUserId, SiteCollectionId, ServerRelativeUrl );

            Response.Redirect ( user.IsADGroup ?
                String.Format ( "{0}{1}?id={2}", ServerRelativeUrl, PortalFileUrls.GroupEdit, spUserId ) :
                String.Format ( "{0}{1}?id={2}", ServerRelativeUrl, PortalFileUrls.UserEdit, spUserId ) );
        }

        protected void btnDisplay_Click ( object sender, EventArgs e )
        {
            LinkButton btnDisplay = ( LinkButton ) sender;
            int spUserId = int.Parse ( btnDisplay.CommandArgument );

            User user = UserModel.GetOrCreateUser ( spUserId, SiteCollectionId, ServerRelativeUrl );

            Response.Redirect ( String.Format ( "{0}{1}?id={2}", ServerRelativeUrl, PortalFileUrls.UserDisplay, spUserId ) );
        }

        protected void rptUsers_ItemDataBound ( object source, RepeaterItemEventArgs e )
        {
            User user = ( User ) e.Item.DataItem;

            #region COLUMN 1
            Image imgPerson = ( Image ) e.Item.FindControl ( "imgPerson" );
            if ( imgPerson != null )
            {
                imgPerson.ImageUrl = user.PictureUrl ?? "/_layouts/images/Kiiro/person-small.jpg";
            }
            LinkButton btnPictureDisplayUser = ( LinkButton ) e.Item.FindControl ( "btnPictureDisplayUser" );
            if ( btnPictureDisplayUser != null )
            {
                btnPictureDisplayUser.CommandArgument = user.SPUserId.ToString ( );
            }
            #endregion

            #region COLUMN 2
            LinkButton btnLinkDisplayUser = ( LinkButton ) e.Item.FindControl ( "btnLinkDisplayUser" );
            if ( btnLinkDisplayUser != null )
            {
                btnLinkDisplayUser.CommandArgument = user.SPUserId.ToString ( );
                btnLinkDisplayUser.Text = SPHelpers.ConvertHtmlToKiiroSafeText ( user.FullName );
            }
            Label lblTitle = ( Label ) e.Item.FindControl ( "lblTitle" );
            if ( lblTitle != null )
            {
                lblTitle.Text = SPHelpers.ConvertHtmlToKiiroSafeText ( user.Title );
            }
            Label lblStatusMessage = ( Label ) e.Item.FindControl ( "lblStatusMessage" );
            if ( lblStatusMessage != null )
            {
                lblStatusMessage.Text = SPHelpers.CheckTextForLinks ( user.StatusNote );
            }
            #endregion

            #region COLUMN 3
            Label lblPhone = ( Label ) e.Item.FindControl ( "lblPhone" );
            if ( lblPhone != null )
            {
                lblPhone.Text = SPHelpers.ConvertHtmlToKiiroSafeText ( user.PhoneNumber );
            }
            HyperLink lnkEmail = ( HyperLink ) e.Item.FindControl ( "lnkEmail" );
            if ( lnkEmail != null )
            {
                lnkEmail.Text = SPHelpers.ConvertHtmlToKiiroSafeText ( user.Email );
                lnkEmail.NavigateUrl = String.Format ( "mailto:{0}", user.Email );
            }
            Label lblIM = ( Label ) e.Item.FindControl ( "lblIM" );
            if ( lblIM != null )
            {
                lblIM.Text = SPHelpers.ConvertHtmlToKiiroSafeText ( user.IM );
            }
            #endregion

            #region COLUMN 4
            Label lblCompanyName = ( Label ) e.Item.FindControl ( "lblCompanyName" );
            if ( lblCompanyName != null )
            {
                lblCompanyName.Text = user.CompanyName != string.Empty ? user.CompanyName : string.Empty;
            }
            #endregion

            #region COLUMN 5
            Label lblIsAdmin = ( Label ) e.Item.FindControl ( "lblIsAdmin" );
            if ( lblIsAdmin != null )
            {
                lblIsAdmin.Text = user.IsAdministrator ? SPHelpers.ConvertHtmlToKiiroSafeText ( "Yes" ) : SPHelpers.ConvertHtmlToKiiroSafeText ( "No" );
            }
            #endregion

            #region COLUMN 6
            LinkButton btnEdit = ( LinkButton ) e.Item.FindControl ( "btnEdit" );
            if ( btnEdit != null )
            {
                btnEdit.Visible = PermissionBitsUsers [ 2 ] && !user.IsSharePointAccount;

                if ( PermissionBitsUsers [ 2 ] )
                {
                    btnEdit.CommandArgument = user.SPUserId.ToString ( );
                }
            }
            LinkButton btnDelete = ( LinkButton ) e.Item.FindControl ( "btnDelete" );
            if ( btnDelete != null )
            {
                btnDelete.Visible = PermissionBitsUsers [ 3 ] && user.SPUserId != CurrentUser.SPUserId && !user.IsSharePointAccount;

                if ( PermissionBitsUsers [ 3 ] )
                {
                    btnDelete.CommandArgument = user.SPUserId.ToString ( );
                }
            }
            #endregion
        }

        private void RePopulatePage ( object sender, EventArgs e )
        {
            PopulatePage ( );
        }

        protected void SortBy_Click ( object sender, EventArgs e )
        {
            LinkButton link = ( LinkButton ) sender;
            if ( V2Pager.SortDirection == SortDirection.Ascending && V2Pager.SortExpression == link.CommandArgument )
                V2Pager.SortDirection = SortDirection.Descending;
            else
                V2Pager.SortDirection = SortDirection.Ascending;
            V2Pager.SortExpression = link.CommandArgument;

            V2Pager.IsSortClick = true;
            V2Pager.DisplayedCount = rptUsers.Items.Count;

            PopulatePage ( );
        }
        #endregion

        #region Methods
        private void PopulatePage ( )
        {
            if ( Users.Count > 0 )
            {
                SortList ( );

                V2Pager.PopulatePager ( Users.Count, Constants.PagerEntity.Users );

                rptUsers.DataSource = Users.GetRange ( V2Pager.PagingIndex, V2Pager.DisplayedCount );
                rptUsers.DataBind ( );

                if ( rptUsers.Items.Count > 0 )
                {
                    HtmlTableRow trUser = ( HtmlTableRow ) rptUsers.Items [ rptUsers.Items.Count - 1 ].FindControl ( "trUser" );
                    trUser.Attributes.Add ( "class", "borderless" );
                }
                else
                {
                    v2Pager.Visible = false;
                    columnHeaders.Visible = false;
                }
            }
        }

        private void SortList ( )
        {
            nameSort.Visible = false;
            companySort.Visible = false;
            adminSort.Visible = false;

            Literal sortText = nameSort;
            string sortTextTemplate = "<img src='/_layouts/images/Kiiro/icon-sort-{0}.gif' />";

            switch ( V2Pager.SortExpression )
            {
                case "Admin":
                    sortText = adminSort;
                    users.Sort ( delegate ( User u1, User u2 ) { return u1.IsAdministrator.CompareTo ( u2.IsAdministrator ); } );
                    break;
                case "Company":
                    sortText = companySort;
                    users.Sort ( delegate ( User u1, User u2 ) { return u1.CompanyName.CompareTo ( u2.CompanyName ); } );
                    break;
                case "Name":
                default:
                    sortText = nameSort;
                    users.Sort ( delegate ( User u1, User u2 ) { return u1.FullName.CompareTo ( u2.FullName ); } );
                    break;
            }

            sortText.Visible = true;

            if ( V2Pager.SortDirection == SortDirection.Ascending )
            {
                sortText.Text = string.Format ( sortTextTemplate, "asc" );
            }
            else
            {
                sortText.Text = string.Format ( sortTextTemplate, "desc" );
                users.Reverse ( );
            }
        }

        private void AddCommandButtons ( )
        {
            if ( PermissionBitsUsers [ 0 ] && LicensingModel.CanIncrementActiveUsersCount ( SiteCollectionId, ServerRelativeUrl ) )
            {
                LinkButton btnCreateUser = new LinkButton ( );
                btnCreateUser.Text = "Add a User";
                btnCreateUser.Attributes.Add ( "class", "icon-add" );
                btnCreateUser.Click += new EventHandler ( btnCreateUser_Click );
                NavigationSub.Commands.Add ( btnCreateUser );

                if ( LicensingModel.HasUnlimitedUsers ( SiteCollectionId, ServerRelativeUrl ) )
                {
                    LinkButton btnCreateGroup = new LinkButton ( );
                    btnCreateGroup.Text = "Add a Group";
                    btnCreateGroup.Attributes.Add ( "class", "icon-add" );
                    btnCreateGroup.Click += new EventHandler ( btnCreateGroup_Click );
                    NavigationSub.Commands.Add ( btnCreateGroup );
                }
            }
        }
        #endregion
    }
}

/*************************************************************************
 * 
 * $Log: /Internal Projects/Kiiro/Kiiro.SiteDefinition/12/TEMPLATE/FEATURES/Kiiro.User/User/AllUsers.aspx.cs $
 * 
 * 34    2/08/10 5:04p Camerons
 * 
 * 33    2/08/10 2:28p Camerons
 * 
 * 32    1/25/10 1:17p Camerons
 * 
 * 31    1/12/10 12:03p Camerons
 * 
 * 30    1/06/10 12:39p Camerons
 * 
 * 29    26/11/09 10:35a Camerons
 * 
 * 28    17/11/09 6:46p Camerons
 * 
 * 27    10/26/09 9:47a Adamw
 * Case 348
 * 
 * 26    5/10/09 11:07a Camerons
 * RE: Create user on demand, checks for HasUnlimitedUser before creating
 * 
 * 25    30/09/09 4:08p Camerons
 * Update all links that point to UserPages, pass User.SPUserId as the
 * ItemId so that we can safely run GetOrCreateUser
 * 
 * 24    30/09/09 2:03p Camerons
 * 
 * 23    30/09/09 1:08p Camerons
 * Implementing UserModel.GetOrCreateUser(). 
 * 
 * 22    29/09/09 5:43p Camerons
 * 
 * 21    29/09/09 3:52p Camerons
 * Changes involving AllUsers.aspx and SPGroups. AllUsers page now
 * displays the recoreds from the SPGroups instead of Kiiro user list.
 * Allows for security to be managed for the SharePoint admin screens. 
 * 
 * 20    29/09/09 2:19p Camerons
 * Implementing User.SPUserId
 * 
 * 19    28/09/09 3:38p Camerons
 * 
 * 18    25/09/09 10:44a Shafia
 * fixed sort method to retain page index and display correct number of
 * rows when sort is clicked.
 * 
 * 17    21/09/09 5:18p Shafia
 * 
 * 16    21/09/09 3:30p Camerons
 * First batch of changes for 1.1.x.x - Security groups update
 * 
 * 15    10/09/09 6:56p Camerons
 * 
 * 14    10/09/09 6:54p Camerons
 * 
 * 13    17/08/09 11:07a Camerons
 * Added check-in comments section
 * 
 ************************************************************************/